#include <ESP32Servo.h>
#include <Arduino.h>
#include "TM1637.h"						  //包含的库

int APin = 22;							    //电机PWM引脚
int ClK=16;
int DLO=17;								      //数码管引脚CLK、DLO
int key[4]={14,27,26,25};				//key引脚

Servo myServo;  						    //舵机对象
TM1637 tm1637(ClK,DLO);					//数码管对象

/****************************主函数*****************************/
void setup() {							    //初始化
	pinMode(APin, OUTPUT);				//电机引脚开
	for (int i = 0; i <4; i++)		//key引脚开
	{
		pinMode(key[i], INPUT_PULLUP);
	}		
	ESP32PWM::allocateTimer(0);			//分配定时器
	myServo.setPeriodHertz(50);			//50hz servo
	myServo.attach(22,500,2500);		//联接引脚22给舵机
	tm1637.init();						      //数码管初始化	
	tm1637.set(BRIGHT_DARKEST);			//数码管亮度设置
	tm1637.point(0);					      //数码管小数点设置
}

void loop() {
	if (digitalRead(key[0])==LOW)		//按下key[0]时
	{
		delay(5);
		while(digitalRead(key[0])==LOW);//等待key[0]松开
		myServo.write(0);				      //舵机0度
		tm1637.clearDisplay();			  //数码管清零
		tm1637.display(0,0);
		tm1637.display(1,0);
		tm1637.display(2,0);
		tm1637.display(3,0);			    //数码管显示0
	}
	else if (digitalRead(key[1])==LOW)//按下key[1]时
	{
	    delay(5);
		while(digitalRead(key[1])==LOW);//等待key[1]松开
		myServo.write(45);				     //舵机45度
		tm1637.clearDisplay();			   //数码管清零
		tm1637.display(0,0);
		tm1637.display(1,0);
		tm1637.display(2,4);
		tm1637.display(3,5);			      //数码管显示45
	}
	else if (digitalRead(key[2])==LOW)//按下key[2]时
	{
	    delay(5);
		while(digitalRead(key[2])==LOW);//等待key[2]松开
		myServo.write(90);				      //舵机90度
		tm1637.clearDisplay();			    //数码管清零
		tm1637.display(0,0);
		tm1637.display(1,0);
		tm1637.display(2,9);
		tm1637.display(3,0);			      //数码管显示90
	}
	else if (digitalRead(key[3])==LOW)	//按下key[3]时
	{
	    delay(5);
		while(digitalRead(key[3])==LOW);//等待key[3]松开
		myServo.write(135);				      //舵机135度
		tm1637.clearDisplay();			    //数码管清零
		tm1637.display(0,0);
		tm1637.display(1,1);
		tm1637.display(2,3);
		tm1637.display(3,5);			      //数码管显示135
	}
}